#include "widget.h"
#include "ui_widget.h"

#include<QMessageBox>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //设置窗口标题
    this->setWindowTitle("客户端");

    //创建socket实例对象
    tcpSocket = new QTcpSocket(this);

    //和服务器建立连接
    tcpSocket->connectToHost("127.0.0.1",9090);

    //连接信号槽处理响应
    connect(tcpSocket,&QTcpSocket::readyRead,this,[=](){
        //读取响应内容
        QString resp = tcpSocket->readAll();
        //把响应内容显示到界面上
        ui->listWidget->addItem("服务器说：" + resp);
    });

    //等待连接建立的结果，确认是否连接成功
    bool ret = tcpSocket->waitForConnected();
    if(!ret)
    {
        QMessageBox::critical(this,"连接服务器出错",tcpSocket->errorString());
        exit(1);
    }
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    QString text = ui->lineEdit->text();
    ui->lineEdit->clear();
    //把请求发送到服务端
    tcpSocket->write(text.toUtf8());
    //把发送的消息显示到界面上
    ui->listWidget->addItem("客户端说：" + text);
}
